package cn.nfwx.tv.helper;

import android.app.Notification;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.entity.UMessage;
import com.umeng.message.tag.TagManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import cn.nfwx.tv.events.AppointEvent;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.SharePrefUtil;

/**
 * Created by zhouzechao on 2017/12/11.
 */

public class UmengPushHelper implements TagManager.TCallBack, Handler.Callback {
    private final String TAG = UmengPushHelper.class.getSimpleName();
    private static UmengPushHelper instance;
    private String mDeviceToken;
    private PushAgent mPushAgent;
    private String aliasType = "nfwx";
    private boolean _hasUpPushId = false;

    private final int DURING = 120 * 1000;
    Handler mHandler = new Handler(this);
    String mChannelName;
    final int ACTION_CHANNEL_TAG = 0;
    final int ACTION_DAY_TAG = 1;
    long mTime;

    public static UmengPushHelper getInstance() {
        if (instance == null) {
            synchronized (UmengPushHelper.class) {
                if (instance == null) {
                    instance = new UmengPushHelper();
                }
            }
        }
        return instance;
    }

    public PushAgent getPushAgent() {
        return mPushAgent;
    }

    public void init(final Context context) {
        mPushAgent = PushAgent.getInstance(context);
        //mPushAgent.setDebugMode(!BuildConfig.IS_RELEASE);
        //mPushAgent.setPushIntentServiceClass(PushIntentService.class);
        //注册推送服务，每次调用register方法都会回调该接口
        //mPushAgent.setEnableForground(NFWXApplication.getInstance(), SharePrefUtil.getPushChoose(NFWXApplication.getInstance()));
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                LogUtil.e(TAG, deviceToken);
                mDeviceToken = deviceToken;
                upPushId(context);
                /**
                 * 开启关闭推送服务
                 */
                if (SharePrefUtil.getPushChoose(context)) {
                    UmengPushHelper.getInstance().open();
                } else {
                    UmengPushHelper.getInstance().close();
                }
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
            }

            @Override
            public void openUrl(Context context, UMessage msg) {
                super.openUrl(context, msg);
            }

            @Override
            public void openActivity(Context context, UMessage msg) {
                Map<String, String> map = msg.extra;
                if (map != null) {
                    if (map.containsKey("gid")) {
                        String gid = map.get("gid");
                        if (!TextUtils.isEmpty(gid)) {
                            SharePrefUtil.saveIjkLiveId(context, gid);
                        }
                    }
                }
                super.openActivity(context, msg);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    LogUtil.e(TAG, key + "---" + value);
                }
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public Notification getNotification(Context context,
                                                UMessage msg) {
                Map<String, String> message = msg.extra;
                // 前台 显示
                AppointEvent.postAppiontEvent(message);
                return super.getNotification(context, msg);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);
    }

    /**
     * 登录或刷新accessToken时, 设备设置别名/账户id绑定.
     *
     * @param accountId
     */
    public void addAccountId(String accountId) {
        if (!TextUtils.isEmpty(accountId)) {
            mPushAgent.addAlias(accountId, aliasType, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    final boolean success = isSuccess;
                }
            });
        }
    }

    /**
     * 更新deviceToken信息
     *
     * @param context
     */
    public void upPushId(final Context context) {
        if (!TextUtils.isEmpty(mDeviceToken) && !_hasUpPushId) {
            _hasUpPushId = true;
            UserManager.upPushId(context, mDeviceToken, SharePrefUtil.getAccessToken(context), null);
        }
    }

    public String getDeviceToken() {
        return mDeviceToken;
    }

    /**
     * 关闭推送
     */
    public void close() {
        mPushAgent.disable(new IUmengCallback() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "close notification");
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }

    /**
     * 开启推送
     */
    public void open() {
        mPushAgent.enable(new IUmengCallback() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "open notification");
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }

    /**
     * 清除标签计时
     */
    public void releaseTag() {
        mHandler.removeCallbacksAndMessages(null);
        mChannelName = "";
    }

    /**
     * 清除频道时间计算
     */
    public void clearChannelTag() {
        mHandler.removeMessages(ACTION_CHANNEL_TAG);
        mChannelName = "";
    }

    /**
     * 设置用户对应得标签
     */
    public void setChannelTag(String channelName) {
        clearChannelTag();
        mChannelName = channelName;
        mHandler.sendEmptyMessageDelayed(ACTION_CHANNEL_TAG, DURING);
    }

    /**
     * 清除一天时间计算
     */
    public void clearDayTag() {
        mHandler.removeMessages(ACTION_DAY_TAG);
    }

    /**
     * 设置用户对应一天的标签
     */
    public void setDayTag() {
        clearDayTag();
        mTime = System.currentTimeMillis();
        mHandler.sendEmptyMessageDelayed(ACTION_DAY_TAG, DURING);
    }

    /**
     * 获取标签
     *
     * @param channelName
     * @return
     */
    private List<String> getChannelTags(String channelName) {
        List<String> tags = new ArrayList<>();
        if (TextUtils.isEmpty(channelName)) {
            return null;
        }

        if (channelName.contains("广东体育")
                || channelName.contains("CCTV5")) {
            tags.add("体育");
        }
        if (channelName.contains("广东新闻")
                || channelName.contains("广东卫视")
                || channelName.contains("北京卫视")
                || channelName.contains("CCTV1")
                || channelName.contains("CCTV13")) {
            tags.add("新闻");
        }
        if (channelName.contains("广东公共")
                || channelName.contains("浙江卫视")
                || channelName.contains("江苏卫视")
                || channelName.contains("CCTV3")) {
            tags.add("综艺");
        }
        if (channelName.contains("TVS2")
                || channelName.contains("珠江")
                || channelName.contains("广东卫视")
                || channelName.contains("东方卫视")
                || channelName.contains("北京卫视")
                || channelName.contains("CCTV8")) {
            tags.add("电视据");
        }
        if (channelName.contains("CCTV6")) {
            tags.add("电影");
        }
        return tags;
    }

    private String getDayTag(int hourDay) {
        if (hourDay >= 0 && hourDay <= 5) {
            return "深夜";
        } else if (hourDay >= 6 && hourDay <= 10) {
            return "早晨";
        } else if (hourDay >= 11 && hourDay <= 13) {
            return "午间";
        } else if (hourDay >= 14 && hourDay <= 17) {
            return "下午";
        } else if (hourDay >= 18 && hourDay <= 24) {
            return "晚间";
        }
        return "";
    }

    @Override
    public void onMessage(boolean isSuccess, ITagManager.Result result) {
        if (isSuccess) {
            Log.i(TAG, "标签设置成功");
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case ACTION_CHANNEL_TAG:
                if (mPushAgent != null) {
                    mPushAgent.getTagManager().getTags(new TagManager.TagListCallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, List<String> results) {
                            if (isSuccess) {
                                List<String> tags = new ArrayList<>();
                                List<String> lists = getChannelTags(mChannelName);
                                for (String tag : lists) {
                                    if (!results.contains(tag)) {
                                        tags.add(tag);
                                    }
                                }
                                if (!tags.isEmpty()) {
                                    String[] tagsArray = new String[tags.size()];
                                    tags.toArray(tagsArray);
                                    if (mPushAgent != null) {
                                        mPushAgent.getTagManager().addTags(UmengPushHelper.this, tagsArray);
                                    }
                                }
                            }
                        }
                    });
                }
                break;
            case ACTION_DAY_TAG:
                if (mPushAgent != null) {
                    mPushAgent.getTagManager().getTags(new TagManager.TagListCallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, List<String> results) {
                            if (isSuccess) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTimeInMillis(mTime);
                                int hourDay = calendar.get(Calendar.HOUR_OF_DAY);
                                String dayTag = getDayTag(hourDay);
                                if (!TextUtils.isEmpty(dayTag)) {
                                    if (!results.contains(dayTag)) {
                                        if (mPushAgent != null) {
                                            mPushAgent.getTagManager().addTags(UmengPushHelper.this, dayTag);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                break;
        }

        return false;
    }
}
